import React, { Component } from 'react';
import Dropdown from '../dropdown';

// interface MentionsProps {
//     values: string[];
//     nameList: string[];
//     onChange: (newValues: string[]) => void;
// }

export default class extends Component {

    state = {
        visible: false,
    };

    onInputChange (e) {
        const value = e.target.value;
        this.setState({ visible: value.endsWith('@') });
        // 如果刚刚输入的值是@ 就添加一个空数组项
        if (value.endsWith('@')) {
            this.props.onChange(this.props.values.concat(''));
        // 否则删除最后一项
        } else {
            const newValues = this.props.values.slice(0, -1);
            this.props.onChange(newValues);
        }
    }

    onSelect (selected) {
        const newValues = this.props.values.concat();
        newValues[newValues.length - 1] = selected.value;
        this.props.onChange(newValues);
    }

    onBlur () {
        // setTimeout处理onSelect和onBlur执行顺序的问题
        setTimeout(() => {
            this.setState({ visible: false });
        }, 200);
    }

    render () {
        const nameStr = this.props.values.map(v => '@' + v).join(' ');
    
        return (
            <>
                <input 
                    style={{ width: '9999px' }}
                    type="text" 
                    value={ nameStr }
                    onChange={ this.onInputChange.bind(this) }
                    // 失焦消失下拉框
                    onBlur={ this.onBlur.bind(this) }
                />
                { 
                    this.state.visible &&
                    <Dropdown 
                        list={ this.props.nameList.map(n => ({ label: n, value: n })) } 
                        onSelect={ this.onSelect.bind(this) }
                    />
                }
            </>
        );
    }

}
